import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import styles from "../style/buynow.module.css";
import leftImg from "../img/left.png";
import { address } from "../api/address"; //收货地址接口
import { score_add } from "../api/score";
interface PurchaseData {
  id: string;
  name: string;
  price: string;
  productTitle: string;
  productImg: string;
  selectedSpec: string;
  quantity: number;
  deliveryAddress: string;
  totalPoints: string;
  productId: string;
}
interface Address {
  id: number;
  name: string;
  tel: string;
  default: number;
  address: string;
}
const BuynowPage = () => {
  const navigate = useNavigate();
  const [quantity, setQuantity] = useState(1);
  const [productId, setProductId] = useState("");
  const [showHint, setShowHint] = useState(false);
  const [productData, setProductData] = useState<PurchaseData | null>(null);
  const [shopID, setShopID] = useState(1);
  const user = JSON.parse(localStorage.getItem("user") || "null"); //用户数据
  console.log(user.data.token, "请求头token");
  console.log(user.data.id, "请求id");
  interface NormItem {
    name: string;
    value: string;
  }
  const [normData, setnormData] = useState<NormItem[]>([]);
  console.log(JSON.stringify(normData));

  // 从本地存储读取商品数据
  useEffect(() => {
    const storedData = localStorage.getItem("currentOrder");
    console.log(storedData, "本地存储中的商品数据");

    if (storedData) {
      try {
        const data: PurchaseData = JSON.parse(storedData);
        const norm: NormItem[] = [
          {
            name: "",
            value: "",
          },
        ];

        norm[0].name = data.name;
        norm[0].value = data.selectedSpec;
        setnormData(norm);
        // norm.name = selectedSpec
        console.log("商品数据解析成功:", data);
        console.log(data.id, "id");
        setShopID(Number(data.id));
        setProductData(data);
        setQuantity(data.quantity);
        setProductId(data.productId);
      } catch (error) {
        console.error("解析商品数据失败:", error);
        navigate("/");
      }
    } else {
      navigate("/");
    }
  }, [navigate]);

  const handleQuantity = (type: "add" | "subtract") => {
    setQuantity((prev) => {
      const newQuantity = Math.max(1, type === "add" ? prev + 1 : prev - 1);
      // 更新本地存储中的数量
      if (productData) {
        const updatedData = { ...productData, quantity: newQuantity };
        localStorage.setItem("currentOrder", JSON.stringify(updatedData));
      }
      return newQuantity;
    });
  };
  // 地址信息渲染
  useEffect(() => {
    fetchAddress();
  }, []);
  const [addressList, setAddressList] = useState<Address[]>([]);
  const [addID, setAddID] = useState<number | null>(null);
  const fetchAddress = async () => {
    const fetchAddress = async () => {
      try {
        const userid = user.data.id;
        const response = await address({
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          data: { uid: userid },
        });
        const res = response.data; // 直接访问 response.data
        console.log(res, "数据");
        setAddressList(res?.data || []);
        setAddID(res?.data[0]?.id);
      } catch (error) {
        console.error("Error fetching addresses:", error);
      }
    };
  };
  const calculateTotal = () => {
    if (!productData) return 0;
    const unitPrice = parseFloat(productData.price);
    const subtotal = unitPrice * quantity;
  };

  // 立即购买接口
  const handleBuy = () => {
    score_add({
      uid: user.data.id,
      address_id: addID,
      id: productId,
      num: quantity,
      norm: "",
      money: productData
        ? (parseFloat(productData.price) * quantity).toFixed(2)
        : "0.00",
    }).then((response) => {
      console.log(response, "立即购买");
      if (response.data.code === 1) {
        navigate("/pointssuccessful");
      }
    });
    if (!productData || quantity < 1) {
      setShowHint(true);
      setTimeout(() => setShowHint(false), 2000);
      return;
    }
    // navigate("/successful");
  };

  if (!productData) {
    return <div className={styles.loading}>加载中...</div>;
  }
  const goBack = () => navigate(-1);
  return (
    <div className={styles.container}>
      {/* 顶部导航 */}
      <div className={styles.top}>
        <div>
          <img onClick={goBack} src={leftImg} alt="" />
          <b>订单购买</b>
        </div>
      </div>
      {/* 地址选择 */}
      <div
        className={styles.addressSection}
        onClick={() => navigate("/address")}
      >
        <div className={styles.addressContent}>
          <span className={styles.addressHint}>
            <span className={styles.addressText}>
              {addressList.length > 0
                ? addressList[0].name + " " + addressList[0].address
                : "请选择收货地址"}
            </span>
          </span>
        </div>
        <img
          src={require("../img/right.png")}
          alt="箭头"
          className={styles.arrowIcon}
        />
      </div>

      {/* 商品信息 */}
      <div className={styles.productCard}>
        <img src={productData.productImg} alt="商品图片" />
        <div className={styles.productInfo}>
          <h3>{productData.productTitle}</h3>
          <p>{productData.selectedSpec}</p>
          <div className={styles.priceRow}>
            <span className={styles.price}>
              ￥{parseFloat(productData.totalPoints).toFixed(2)}
            </span>
            <div className={styles.quantityControl}>
              <button
                className={styles.quantityControlButton}
                onClick={() => handleQuantity("subtract")}
                aria-label="减少数量"
                style={{
                  fontSize: "24px",
                  lineHeight: "1",
                  padding: "0 12px",
                }}
              >
                -
              </button>
              <input
                type="number"
                value={quantity}
                onChange={(e) => {
                  const newQuantity = Math.max(1, +e.target.value);
                  setQuantity(newQuantity);
                  const updatedData = { ...productData, quantity: newQuantity };
                  localStorage.setItem(
                    "currentOrder",
                    JSON.stringify(updatedData)
                  );
                }}
                aria-label="购买数量"
                min="1"
                style={{
                  width: "40px",
                  textAlign: "center",
                  margin: "0 5px",
                }}
              />
              <button
                className={styles.quantityControlButton}
                onClick={() => handleQuantity("add")}
                aria-label="增加数量"
                style={{
                  fontSize: "24px",
                  lineHeight: "1",
                  padding: "0 12px",
                }}
              >
                +
              </button>
            </div>
          </div>
        </div>
      </div>

      {/* 底部操作栏 */}
      <div className={styles.footer}>
        <div className={styles.total}>
          总价:{" "}
          <span>
            ￥{(parseFloat(productData.totalPoints) * quantity).toFixed(2)}
          </span>
        </div>
        {/* onClick={handleBuy} */}
        <button className={styles.buyButton} onClick={handleBuy}>
          立即购买
        </button>
      </div>

      {/* 提示信息 */}
      {showHint && (
        <div className={styles.hintBox}>
          <div className={styles.hintMessage}>输入框不得为空！</div>
        </div>
      )}
    </div>
  );
};

export default BuynowPage;
